﻿Namespace BoAddon
    ''' <summary>
    ''' BoAddon项目中的启动类的基类
    ''' 实现了工作目录下的BoAddonBiz的自动加载
    ''' 注意：继承后需要手工添加Main（）静态方法，并实例化子类。
    ''' </summary>
    ''' <remarks></remarks>
    Public MustInherit Class BoAddonBase
        Private _B1Connected As Boolean
        Private Shared _BoAddonBase As BoAddonBase

        Sub New()
#If Not Debug Then
            Dim sd As Date = Date.Now
            Console.WriteLine("**************************************开始计时 BoAddonBase.Initialization***************************************************************" & sd.ToString("yyyy-MM-dd HH:mm:ss.fff"))
#End If
            Initialization()
#If Not Debug Then
            Dim ed As Integer = DateDiff(DateInterval.Second, sd, Date.Now)
            Console.WriteLine("**************************************结束计时***************************************************************" & ed.ToString())
#End If
        End Sub

        Public ReadOnly Property ProceesName As String
            Get
                Return Process.GetCurrentProcess.ProcessName
            End Get
        End Property

        Public Overridable ReadOnly Property BoAddonBizSign As String
            Get
                Return "BoAddonBiz_"
            End Get
        End Property

        Public Overridable ReadOnly Property RunLimit As Integer
            Get
                Return 1
            End Get
        End Property

        Public Overridable ReadOnly Property WorkFolder As String
            Get
                Return SAPBoAddon.B1Addon.B1Addon.FolderWork
            End Get
        End Property

        Private Sub Initialization()
            Try
#If Not Debug Then
                Dim sd As Date = Date.Now
                Console.WriteLine(" 开始计时 检查线程 " & sd.ToString("yyyy-MM-dd HH:mm:ss.fff") & " ***************************************************************")
#End If
                If getExistProcess() < RunLimit Then
#If Not Debug Then
                    Dim ed As Integer = DateDiff(DateInterval.Second, sd, Date.Now)
                    Console.WriteLine(" 结束计时 检查线程 " & Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") & "  " & ed.ToString() & " ***************************************************************")
                    sd = Date.Now
                    Console.WriteLine(" 开始计时 连接B1 " & sd.ToString("yyyy-MM-dd HH:mm:ss.fff") & " ***************************************************************")
#End If

                    If Me.ConnectB1() = 0 Then
#If Not Debug Then
                        ed = DateDiff(DateInterval.Second, sd, Date.Now)
                        Console.WriteLine(" 结束计时 连接B1 " & Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") & "  " & ed.ToString() & " ***************************************************************")
                        sd = Date.Now
                        Console.WriteLine(" 开始计时 加载DLL " & sd.ToString("yyyy-MM-dd HH:mm:ss.fff") & " ***************************************************************")
#End If
                        Me.LoadAllBusiness(WorkFolder)
#If Not Debug Then
                        ed = DateDiff(DateInterval.Second, sd, Date.Now)
                        Console.WriteLine(" 结束计时 加载DLL " & Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") & "  " & ed.ToString() & " ***************************************************************")
                        sd = Date.Now
                        Console.WriteLine(" 开始计时 Add-On事件 " & sd.ToString("yyyy-MM-dd HH:mm:ss.fff") & " ***************************************************************")
#End If
                    End If
                    Dim oEvent As New SAPBoAddon.B1AddonBase.AddonEvent(B1AddonBase.EnumBaseEventType.et_AddonIsRuning)
#If Not Debug Then
                    ed = DateDiff(DateInterval.Second, sd, Date.Now)
                    Console.WriteLine(" 结束计时 Add-On事件 " & Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") & "  " & ed.ToString() & " ***************************************************************")
                    sd = Date.Now
                    Console.WriteLine(" 开始计时 RaiseAddonEvent事件 " & sd.ToString("yyyy-MM-dd HH:mm:ss.fff") & " ***************************************************************")
#End If
                    oEvent.BeforeEvent = False
                    oEvent.ActionSucess = True
                    SAPBoAddon.B1Addon.B1Addon.SBOAddOn.RaiseAddonEvent(oEvent)
#If Not Debug Then
                    ed = DateDiff(DateInterval.Second, sd, Date.Now)
                    Console.WriteLine(" 结束计时 RaiseAddonEvent事件 " & Date.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") & "  " & ed.ToString() & " ***************************************************************")
#End If
                    System.Windows.Forms.Application.Run()
                Else
                    Throw New Exception(Me.ProceesName & "已存在实例。")
                End If
            Catch ex As Exception
                System.Windows.Forms.MessageBox.Show(ex.Message, My.Application.Info.Title)
            End Try
        End Sub

        ''' <summary>
        ''' 返回解决方案字符串
        ''' （用来申请License）
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Protected MustOverride ReadOnly Property addOnIdentifier() As String

        ''' <summary>
        ''' 返回DI初始化方式
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Protected MustOverride ReadOnly Property ConnectionType As B1Connections.ConnectionType

        ''' <summary>
        ''' 获取已运行的线程数
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function getExistProcess() As Integer
            Dim ProcessAll() As Process
            Dim ProcessOne As Process
            Dim ExistCount As Integer
            Try
                '检查是否已运行实例
                ProcessAll = Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName)
                ExistCount = 0
                For Each ProcessOne In ProcessAll
                    If ProcessOne.Id <> Process.GetCurrentProcess.Id Then
                        If ProcessOne.SessionId = Process.GetCurrentProcess.SessionId Then
                            ProcessOne.Kill()
                            'ExistCount += 1
                        End If
                    End If
                Next
                Return ExistCount
            Catch ex As Exception
                Throw ex
            End Try
        End Function

        Public ReadOnly Property B1Connected As Boolean
            Get
                Return _B1Connected
            End Get
        End Property

        Private ReadOnly Property ConnectString As String
            Get
                If (System.Environment.GetCommandLineArgs().Length = 1) Then
                    Return SAPBoAddon.B1Connections.CreateInstance.connStr
                Else
                    Return System.Environment.GetCommandLineArgs().GetValue(1).ToString()
                End If
            End Get
        End Property
        ''' <summary>
        ''' 连接B1
        ''' </summary>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Protected Overridable Function ConnectB1() As Integer
            Dim retCode As Integer
            Try
                retCode = SAPBoAddon.B1Addon.B1Addon.Connected(ConnectString, addOnIdentifier, ConnectionType)
                _B1Connected = True
                Return retCode
            Catch ex As Exception
                Throw ex
            End Try
        End Function

        ''' <summary>
        ''' 加载工作目录下B1Console
        ''' </summary>
        ''' <param name="WorkFolder"></param>
        ''' <remarks></remarks>
        Protected Overridable Sub LoadAllBusiness(ByVal WorkFolder As String)
            For Each filePathOne As String In System.IO.Directory.GetFiles(WorkFolder)
                If getFileName(filePathOne) Like Me.BoAddonBizSign & "*.dll" Then
                    Me.CreateBusinessConsoleInstance(System.IO.File.ReadAllBytes(filePathOne))
                End If
            Next
            Dim oEvent As New SAPBoAddon.B1AddonBase.AddonEvent(B1AddonBase.EnumBaseEventType.et_BusinessToLoad)
            oEvent.BeforeEvent = False
            oEvent.ActionSucess = True
            SAPBoAddon.B1Addon.B1Addon.SBOAddOn.RaiseAddonEvent(oEvent)
        End Sub

        Private Function getFileName(ByVal filePath As String) As String
            Dim fileName As String = ""
            If filePath Like "*:\*" Then
                fileName = filePath.Substring(filePath.LastIndexOf("\") + 1, filePath.Length - filePath.LastIndexOf("\") - 1)
            End If
            Return fileName
        End Function

        ''' <summary>
        ''' 实例化B1console
        ''' </summary>
        ''' <param name="asmFile"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function CreateBusinessConsoleInstance(ByVal asmFile As Byte()) As B1BusinessConsole
            Dim asm As System.Reflection.Assembly
            Dim B1Console As B1BusinessConsole = Nothing
            asm = System.Reflection.Assembly.Load(asmFile)
            If Not asm Is Nothing Then
                B1Console = B1BusinessConsole.CreateInInstance(asm)
            End If
            Return B1Console
        End Function



    End Class
End Namespace

